package com.example.yam.greenapp;

import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link ShopCarFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link ShopCarFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ShopCarFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    //各种设置
    //常量
    private static final String TAG="ShopCarFragment";
    public String MyUrl=MyApplication.localhost+"Green/index.php/indexg/shopCar/id/"+MyApplication.user.getId()+"/stnum/";
    public int stnum = -1;
    //控件
    private View view;
    private SwipeRefreshLayout swipeRefreshLayout = null;
    private ListView listView = null;
    public DingdansAdapter dingdansAdapter;

    //适配器
    private List<Dingdan> dingdanList = new ArrayList<Dingdan>();//list

    public ShopCarFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment IndexFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ShopCarFragment newInstance(String param1, String param2) {
        ShopCarFragment fragment = new ShopCarFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        this.view = inflater.inflate(R.layout.fragment_shopcar, container,false);
        this.listView = (ListView) this.view.findViewById(R.id.shopcarlist);//订单列表
        this.swipeRefreshLayout = (SwipeRefreshLayout) this.view.findViewById(R.id.shopcar_swip);
        dingdansAdapter = new DingdansAdapter(super.getActivity(),R.layout.dingdanlist,dingdanList);
        getMessage();
        //添加监听事件
        this.swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener(){
            @Override
            public void onRefresh() {
                Log.v(TAG,"刷新");
                stnum+=5;
                //设置列表数据
                String nurl = MyUrl+stnum;
                //设置数据列表
                VolleyGetString(nurl);
                dingdansAdapter.notifyDataSetChanged();
                swipeRefreshLayout.setRefreshing(false);
            }
        });
        this.listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent it = new Intent(getActivity(),DlistActivity.class);
                it.putExtra("dnum",dingdanList.get(position).getDnum());

                startActivity(it);
            }
        });
        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    private void getMessage(){//获取购物车信息
        VolleyGetString(this.MyUrl+"0");
        Log.d(TAG, "完成了");
    }
    //使用volley获取数据
    private void VolleyGetString(String url){
        RequestQueue mQueue = MyApplication.getHttpQueue();
        Log.d(TAG, "开始了");
        Log.d(TAG, url);
        StringRequest stringRequest = new StringRequest(url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {//正确搜索到数据
                        Log.d(TAG, response);
                        parseJSONobject(response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, error.getMessage(), error);
            }
        });
        mQueue.add(stringRequest);
    }
    //json解析
    private void parseJSONobject(String ss){
        try{
             Log.d(TAG,"数据是"+ss);
            JSONObject jsb = new JSONObject(ss);
            JSONArray jsonArray=(JSONArray) new JSONArray(jsb.getString("dingdan"));
            //订单列表数据布置
            for(int i=0;i<jsonArray.length();i++){
                JSONObject jb=jsonArray.getJSONObject(i);
                Log.v(TAG,jb.getString("dnum"));
                Dingdan d = new Dingdan(jb.getString("id"), jb.getString("dnum"), jb.getString("uid"),jb.getString("uname"),
                        jb.getString("total"),jb.getString("receiver"),jb.getString("address"),jb.getString("phone"),
                        jb.getString("flag"),jb.getString("time"));
                dingdanList.add(d);
            }
            this.listView.setAdapter(dingdansAdapter);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
